"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : 故障&可靠性测试&配置文件
Case Name   : 配置文件丢失
Create At   : 2020/06/29
Owner       : n@ningyali
Description :
    1.备机启动/停止
    2.备机删除配置文件
    3.备机重建（预期失败）
    4.恢复配置文件
    5.备机重建（预期成功）
Expect      :
    1.成功
    2.成功
    3.失败
    4.成功
    5.成功
History     :
    Modified by @wan005 2022/04/20 : 优化备份文件夹 优化注释信息
    Modified by @zou_jialiang050 2022/04/26 : 确认备份文件夹是否存在，不存在则新建备份文件夹
"""

import os
import sys
import time
import unittest
from yat.test import Node
from yat.test import macro

sys.path.append(sys.path[0] + "/../")
from testcase.utils.Logger import Logger
from testcase.utils.Constant import Constant
from testcase.utils.Common import Common
from testcase.utils.CommonSH import CommonSH


class ConfParamLost(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        cls.log = Logger()
        cls.log.info(f'-----{os.path.basename(__file__)} start-----')
        cls.conf_file_path = os.path.join(macro.DB_INSTANCE_PATH, macro.DB_PG_CONFIG_NAME)
        cls.env_path = macro.DB_ENV_PATH
        cls.primaryNode = Node(node='PrimaryDbUser')
        cls.standbyNode = Node(node='Standby1DbUser')
        cls.com = Common()
        cls.Constant = Constant()
        cls.primary_sh = CommonSH('PrimaryDbUser')
        cls.standby_sh = CommonSH('Standby1DbUser')

        # 获取备机名称
        get_hostname_cmd = 'cat /etc/hostname'
        cls.log.info(get_hostname_cmd)
        cls.hostname = cls.standbyNode.sh(get_hostname_cmd).result()
        cls.log.info(cls.hostname)

    def setUp(self):
        self.log.info('--------------创建备份文件夹--------------------------- ')
        is_dir_exists_cmd = f'''if [ ! -d "{macro.DB_BACKUP_PATH}" ]
                                            then
                                                mkdir {macro.DB_BACKUP_PATH}
                                            fi'''
        result = self.standbyNode.sh(is_dir_exists_cmd).result()
        self.log.info(result)

        self.log.info('----------------------------初始化-----------------------------')
        db_status = self.primary_sh.getDbClusterStatus('status')
        if not db_status:
            self.primary_sh.startDbCluster()

            db_status = self.primary_sh.getDbClusterStatus('status')
            if not db_status:
                raise Exception("db status is not true, please check!")
        self.log.info(db_status)

    # 备机启动时，配置文件丢失
    def test_1_start_lost(self):
        # 备机删除配置文件
        del_cmd = f'mv {self.conf_file_path} {macro.DB_BACKUP_PATH}'
        self.log.info(del_cmd)
        del_msg = self.standbyNode.sh(del_cmd).result()
        self.log.info(del_msg)
        self.assertEqual(del_msg, '')

        time.sleep(5)

        # 备机重建
        rebuild_msg = self.standby_sh.executeGsctl('build', self.Constant.REBUILD_SUCCESS_MSG, '-b full')
        self.log.info(rebuild_msg)
        self.assertFalse(rebuild_msg)

    # 备机停止时，配置文件丢失
    def test_2_stop_lost(self):
        # 备机停止数据库
        stop_cmd = f"source {self.env_path}; gs_om -t stop -h {self.hostname}"
        self.log.info(stop_cmd)
        stop_msg = self.standbyNode.sh(stop_cmd).result()
        self.log.info(stop_msg)
        self.assertIn(self.Constant.STOP_NODE_SUC_MSG, stop_msg)

        # 备机删除配置文件
        del_cmd = f'mv {self.conf_file_path} {macro.DB_BACKUP_PATH}'
        self.log.info(del_cmd)
        del_msg = self.standbyNode.sh(del_cmd).result()
        self.log.info(del_msg)
        self.assertEqual(del_msg, '')

        # 备机重建
        rebuild_msg = self.standby_sh.executeGsctl('build', self.Constant.REBUILD_SUCCESS_MSG, '-b full')
        self.log.info(rebuild_msg)
        self.assertFalse(rebuild_msg)

    def tearDown(self):
        self.log.info("恢复配置文件")
        recover_cmd = f'mv {macro.DB_BACKUP_PATH}/{os.path.basename(self.conf_file_path)} {os.path.dirname(self.conf_file_path)}'
        self.log.info(recover_cmd)
        recover_msg = self.standbyNode.sh(recover_cmd).result()
        self.log.info(recover_msg)
        self.assertEqual(recover_msg, '')

        time.sleep(5)

        self.log.info("备机重建")
        rebuild_msg = self.standby_sh.executeGsctl('build', self.Constant.REBUILD_SUCCESS_MSG, '-b full')
        self.log.info(rebuild_msg)
        self.assertTrue(rebuild_msg)

    @classmethod
    def tearDownClass(cls):
        cls.log = Logger()
        cls.log.info(f'-----{os.path.basename(__file__)} end-----')
